package com.mmlc.meimei.lichengkongjian.mine;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.responsejavabean.RequestError;
import com.androidnetframe.utils.LogUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.App;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.dialog.CustomDialog;
import com.mmlc.network.filter.ChangeInfoRequestFilter;
import com.mmlc.network.filter.ChangePasswordRequestFilter;
import com.mmlc.network.filter.LoginOutRequestFilter;
import com.mmlc.network.filter.UploadImgRequestFilter;
import com.mmlc.network.responsebean.ChangeInfoResponseBean;
import com.mmlc.utils.Constants;
import com.mmlc.utils.EditInputUtils;
import com.mmlc.utils.FileManager;
import com.mmlc.utils.ImageTools;
import com.mmlc.utils.PermissionUtils;
import com.mmlc.utils.ToastUtils;
import com.squareup.picasso.Picasso;
import com.yongchun.library.view.ImageSelectorActivity;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;


public class ActivityMyinfo extends InterActivity implements View.OnClickListener,ActivityCompat.OnRequestPermissionsResultCallback {

    @InjectView(R.id.tv_title)
    TextView tv_title;
    @InjectView(R.id.iv_back)
    ImageView ivBack;
    @InjectView(R.id.tv_suninfo)
    TextView tv_sub;
    @InjectView(R.id.iv_photo)
    RoundedImageView ivPhoto;
    @InjectView(R.id.tv_nickName)
    RelativeLayout tvNickName;
    @InjectView(R.id.tv_gender)
    TextView tvGender;
    @InjectView(R.id.tv_sex)
    RelativeLayout tvSex;
    @InjectView(R.id.rl_password)
    RelativeLayout rlPassword;
    @InjectView(R.id.rl_bottom)
    RelativeLayout rlBottom;
    @InjectView(R.id.sv_scrollView)
    ScrollView svScrollView;
    @InjectView(R.id.tv_name)
    TextView tvBuyName;
    @InjectView(R.id.rootView)
    RelativeLayout rootView;
    @InjectView(R.id.rl_clearCache)
    RelativeLayout rlClearCache;
    @InjectView(R.id.rl_loginOut)
    RelativeLayout rlLoginOut;

    @Override
    protected int initContentView() {
        return R.layout.activity_myinfo;
    }

    @Override
    protected void initView() {
        ButterKnife.inject(this);
        processData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        String nichen = App.user.getNickName();
        if (!TextUtils.isEmpty(nichen)) {
            tvBuyName.setText(nichen);
        } else {
            tvBuyName.setHint("取一个好听的昵称吧");
        }
        String sex = App.user.getSex();
        tvGender.setText(sex);
    }

    private void processData() {
        processTitleBar();
        //初始化界面
        initUI();
        rlClearCache.setOnClickListener(this);
        rlLoginOut.setOnClickListener(this);

    }

    private void processTitleBar() {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_title.setText("设置");
        tv_sub.setVisibility(View.VISIBLE);
        tv_sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tmpheader = "";
                if (currentHeadPhoto == null) {
                    tmpheader = "";
                } else {
                    tmpheader = currentHeadPhoto;
                }

                //将头像，昵称，性别提交上去，昵称和性别是必须上传上去
                String gender = tvGender.getText().toString();
                int type = 0;
                if (gender.equals("男")) {
                    type = 1;
                } else if(gender.equals("女")){
                    type = 2;
                }else if(gender.equals("保密")){
                    type = 0;
                }

                if (TextUtils.isEmpty(tmpheader)) {
                    changeInfo("", tvBuyName.getText().toString(), type);
                } else {
                    commitPhoto(tmpheader, type);
                }

            }
        });

    }

    private void commitPhoto(final String tmpheader, final int type) {

        UploadImgRequestFilter imgFilter = new UploadImgRequestFilter(ActivityMyinfo.this);
        imgFilter.requestParams.addBodyParameter("imgFile", new File(tmpheader));
        imgFilter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (!TextUtils.isEmpty(tmpheader)) {
                        App.user.savePhoto(tmpheader);
                    }
                    changeInfo(data.optString("path"), tvBuyName.getText().toString(), type);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);
            }
        });
    }

    private void initUI() {

        String nichen = App.user.getNickName();

        if (!TextUtils.isEmpty(nichen)) {
            tvBuyName.setText(nichen);
        } else {
            tvBuyName.setHint("取一个好听的昵称吧");
        }
        String sex = App.user.getSex();
        tvGender.setText(sex);
        String photoPath = App.user.getPhoto();
        if(!TextUtils.isEmpty(photoPath)) {
            LogUtils.e("photoPath",photoPath);
            Picasso.with(context)
                    .load(photoPath)
                    .fit()
                    .into(ivPhoto);
        }else{
            ivPhoto.setImageDrawable(getResources().getDrawable(R.drawable.avatar_default));
        }
    }

    @Override
    protected void initEvent() {

    }

    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PermissionUtils.CODE_READ_EXTERNAL_STORAGE:
                    PermissionUtils.requestPermission(ActivityMyinfo.this, PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE, mPermissionGrant);
                    break;
                case PermissionUtils.CODE_WRITE_EXTERNAL_STORAGE:
                    PermissionUtils.requestPermission(ActivityMyinfo.this, PermissionUtils.CODE_CAMERA, mPermissionGrant);
                    break;
                case PermissionUtils.CODE_CAMERA:
                    selectPhoto();
                    break;
                default:
                    PermissionUtils.requestPermission(ActivityMyinfo.this, PermissionUtils.CODE_READ_EXTERNAL_STORAGE, mPermissionGrant);
                    break;
            }
        }
    };

    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
    }

    @OnClick({R.id.iv_photo, R.id.tv_nickName, R.id.tv_sex, R.id.rl_password})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_photo:
                //6.0动态获取权限 相册 相机
                PermissionUtils.requestPermission(this, PermissionUtils.CODE_READ_EXTERNAL_STORAGE, mPermissionGrant);
                break;
            case R.id.tv_nickName:
                changeNickName(R.layout.popup_changenickname);
                break;
            case R.id.tv_sex:
                selectSex(R.layout.popup_select_sex);
                break;
            case R.id.rl_password:
                changePassword(R.layout.popup_change_password);
                break;
            case R.id.rl_clearCache:
                clearCache();
                break;
            case R.id.rl_loginOut:
                loginOut();
                break;
        }
    }

    private void loginOut() {
        showLoginOut();
    }

    private void showLoginOut() {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("退出登陆");
        builder.setMessage("真的要退出吗？");
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                requestLoginOUtFromServer();
            }
        });
        builder.create().show();
    }

    private void requestLoginOUtFromServer() {
        final LoginOutRequestFilter filter = new LoginOutRequestFilter(this);
        filter.offerErrorParams(rootView);
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<String>() {
            @Override
            public void onSuccess(String result) {
                ToastUtils.showToast("退出登陆成功");
                App.user.setLoginState(false);
                App.user.removePassword();
                filter.saveTokenId(null);
                finish();
//                UIUtils.simpleStartActivity(LoginActivity.class);
                Intent intent = new Intent(ActivityMyinfo.this, LoginActivity.class);
                intent.putExtra("LoginOut", "LoginOut");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);
            }
        });
    }

    private void clearCache() {
        x.image().clearMemCache();
        FileManager.delete(Constants.DIR_CACHE);
        ToastUtils.showToast("清除成功");
    }


    private void selectPhoto() {
        ImageSelectorActivity.start(this,1,ImageSelectorActivity.MODE_SINGLE,true,true,true);
    }


    public static final int REQUEST_IMAGE  =100;
    String currentHeadPhoto = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == ImageSelectorActivity.REQUEST_IMAGE){
            ArrayList<String> images = (ArrayList<String>) data.getSerializableExtra(ImageSelectorActivity.REQUEST_OUTPUT);
            // do something
            String picPath = images.get(0);
            LogUtils.e("ABCDE",picPath);
            Bitmap bitmap = BitmapFactory.decodeFile(picPath);
            currentHeadPhoto =  ImageTools.savePhotoToSDCard(bitmap, Environment.getExternalStorageDirectory().getAbsolutePath(), String.valueOf(System.currentTimeMillis()));
            //由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
            //将处理过的图片显示在界面上，并保存到本地

            Picasso.with(this).load(new File(picPath)).fit().into(ivPhoto);
            bitmap.recycle();
        }
    }

    private void changePassword(int layout) {
        View view = showEdit(layout);
        final EditText et_oldPassword = (EditText) view.findViewById(R.id.et_oldPassword);
        final EditText et_newPassword = (EditText) view.findViewById(R.id.et_newPassword);
        final EditText et_confirmPassword = (EditText) view.findViewById(R.id.et_confirmPassword);
        Button bt_ok = (Button) view.findViewById(R.id.bt_ok);
        bt_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //确定旧密码是否正确
                if (!App.user.getPassword().equals(et_oldPassword.getText().toString())) {
                    ToastUtils.showToast(getApplicationContext(), "旧密码输入错误");
                    return;
                }
                //比较新密码是否正确
                if (!et_newPassword.getText().toString().equals(et_confirmPassword.getText().toString())) {
                    ToastUtils.showToast(getApplicationContext(), "两次输入的新密码不匹配");
                    return;
                }
                boolean isPassword = EditInputUtils.checkPassword(getApplicationContext(), et_confirmPassword.getText().toString());
                if (!isPassword) {
                    return;
                }
                //将修改信息提交到服务器
                ChangePasswordRequestFilter filter = new ChangePasswordRequestFilter(ActivityMyinfo.this);
                filter.offerErrorParams(rootView);
                filter.requestBean.old_password = et_oldPassword.getText().toString();
                filter.requestBean.new_password = et_newPassword.getText().toString();
                filter.requestBean.method = "modifyPwd";
                filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<Object>() {

                    @Override
                    public void onSuccess(Object result) {
                        ToastUtils.showToast(getApplicationContext(), "密码修改成功");
                        //保存新密码
                        App.user.setPassword(et_confirmPassword.getText().toString());
                        //关闭弹出框
                        closeDialog();
                    }

                    @Override
                    public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                        ToastUtils.showToast(serverError.mess.toString());
                    }
                });

            }
        });

    }

    private void selectSex(int popup_select_sex) {
        View view = showEdit(popup_select_sex);
        RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.rg_select);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedID) {
                //设置性别
                switch (checkedID) {
                    case R.id.rb_secret:
                        tvGender.setText("保密");
                        App.user.saveSex(0);
                        break;
                    case R.id.rb_man:
                        tvGender.setText("男");
                        App.user.saveSex(1);
                        break;
                    case R.id.rb_woman:
                        tvGender.setText("女");
                        App.user.saveSex(2);
                        break;
                }
                //关闭弹出框
                closeDialog();
            }

        });

    }

    private void changeNickName(int layoutId) {
        View view = showEdit(layoutId);
        final EditText et_nickName = (EditText) view.findViewById(R.id.et_nickName);
        Button bt_confim = (Button) view.findViewById(R.id.bt_confim);
        bt_confim.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //设置新的昵称
                String nickName = et_nickName.getText().toString();

                if (EditInputUtils.checkName(ActivityMyinfo.this, nickName)) {
                    tvBuyName.setText(nickName);
                    //关闭弹出框
                    closeDialog();
                } else {
                    ToastUtils.showToast(getApplicationContext(), "用户名不合法");
                }
            }
        });
    }

    PopupWindow popupWindow;

    CustomDialog dialog;

    public View showEdit(int layoutId) {
        if (dialog == null) {
            dialog = new CustomDialog(ActivityMyinfo.this);
        }
        dialog.setView(layoutId);
        dialog.show();
        return dialog.getContentView();
    }

    public void changeInfo(final String imageStrig, final String nichen, final int sex) {
        ChangeInfoRequestFilter filter = new ChangeInfoRequestFilter(ActivityMyinfo.this);
        filter.offerErrorParams(rootView);
        filter.isTransparence = true;
        filter.requestBean.method = "modify";
        filter.requestBean.header = imageStrig;
        filter.requestBean.nichen = nichen;
        filter.requestBean.sex = sex;
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<ChangeInfoResponseBean>() {

            @Override
            public void onSuccess(ChangeInfoResponseBean result) {
                ToastUtils.showToast(getApplicationContext(), "修改成功");
                //保存昵称
                App.user.saveSex(sex);
                App.user.saveNickName(nichen);
                //保存性别
                //保存用户头像

                setResult(200);

                if (TextUtils.isEmpty(imageStrig)) {
                    return;
                }
                // Bitmap bitmap = BitmapFactory.decodeByteArray(imageStrig.getBytes(), 0, imageStrig.getBytes().length);
                App.user.savePhoto(result.getData().getHeader_thumb());

            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(getApplicationContext(), "修改失败");
            }
        });
    }

    public void closeDialog() {
        if (dialog != null && dialog.dialog.isShowing()) {
            dialog.dialog.dismiss();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.inject(this);
    }
}
